package cn.edu.xzit.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyControler {
    @RequestMapping({"/index", "/"})
    public String toIndex(Model model) {
        model.addAttribute("msg", "hello shiro");
        return "index";
    }

    @RequestMapping("/login")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/doLogin")
    public String doLogin(String username, String password, Model model) {
        //封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        //执行登录的方法，只要没有异常代表登录成功
        try {
            currentUser.login(token);
            return "index";
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "index";
    }
}
